package jgl.vajra.kingkong.part.vehicle.activity;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.ZoomControls;

import com.alibaba.fastjson.JSONObject;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import jgl.vajra.kingkong.R;
import jgl.vajra.kingkong.bean.MarketPriceBean;
import jgl.vajra.kingkong.bean.OrderParametersBean;
import jgl.vajra.kingkong.databinding.ActivityWaitingOrderBinding;
import jgl.vajra.kingkong.event.OrderPageListEvent;
import jgl.vajra.kingkong.event.PushDanmuInfoEvent;
import jgl.vajra.kingkong.event.PushDriversNumEvent;
import jgl.vajra.kingkong.event.PushReceivedSuccessEvent;
import jgl.vajra.kingkong.manager.AccountManager;
import jgl.vajra.kingkong.manager.IntentManager;
import jgl.vajra.kingkong.netty.MessageBody;
import jgl.vajra.kingkong.part.home.activity.HomeActivity;
import jgl.vajra.kingkong.part.home.pop.ModifyPricePop;
import jgl.vajra.kingkong.part.vehicle.contract.WaitingOrderContract;
import jgl.vajra.kingkong.part.vehicle.pop.RewardPop;
import jgl.vajra.kingkong.part.vehicle.viewModel.WaitingOrderViewModel;
import jgl.vajra.kingkong.view.CountDownView;
import jgl.vajra.kingkong.view.bulletChat.DanMuHelper;
import jgl.vajra.kingkong.view.bulletChat.DanmakuEntity;
import jgl.vajra.kingkong.view.bulletChat.Danmu;
import jgl.vajra.kingkong.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.kingkong.widget.mvvm.view.AppActivityManager;
import jgl.vajra.kingkong.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.kingkong.widget.retrofithelper.rxsubscriber.CommonObserver;
import jgl.vajra.kingkong.widget.utils.TimeUtils;
import jgl.vajra.kingkong.widget.utils.ToastUtils;
import jgl.vajra.kingkong.widget.utils.UIUtils;

@CreateViewModel(WaitingOrderViewModel.class)
public class WaitingOrderActivity extends BaseMVVMActivity<WaitingOrderViewModel, ActivityWaitingOrderBinding> implements WaitingOrderContract.View {

    private BaiduMap mBaiduMap;
    private MapStatus mapBuild;
    private RewardPop rewardPop;
    private ModifyPricePop modifyPricePop;
    private String order;
    private String authorization;
    private MarketPriceBean marketPriceBean;
    private int miss = 0;
    private String amount;
    private OrderParametersBean orderParameters;
    private boolean type;
    private String orderTime;

    private Handler mDanmuAddHandler;
    private boolean continueAdd;
    private int counter;

    private boolean isBarrage = false;
    private List<Danmu> danmuList = new ArrayList<>();
    private int num = 0;//循环的数量
    private DanMuHelper mDanMuHelper;
    private long period = 15;//秒

    @Override
    public int getLayoutId() {
        return R.layout.activity_waiting_order;
    }

    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);

        order = getIntent().getStringExtra("order");
        orderParameters = getIntent().getParcelableExtra("orderParameters");
        marketPriceBean = getIntent().getParcelableExtra("marketPriceBean");
        amount = getIntent().getStringExtra("amount");
        orderTime = getIntent().getStringExtra("orderTime");
        type = getIntent().getBooleanExtra("type", false);
        mBinding.tvPrice.setText(amount);

        authorization = AccountManager.getInstance().getLoginData(UIUtils.getContext()).authorization;

        if (orderParameters.priceType == 0) {
            mBinding.tvPriceText.setText("打赏小费");
        } else {
            mBinding.tvPriceText.setText("修改价格");
        }

        if (type) {

            long countDown = (System.currentTimeMillis() - TimeUtils.parsStringTimeHmLong(orderTime));
            miss = (int) (countDown / 1000);
            sequentialTiming();
        }

        //开始扩散
        mBinding.diffuseView.start();
        //结束扩散
//        mBinding.diffuseView.stop();


        mBinding.countDownView.setOnCountDownListener(new CountDownView.OnCountDownListener() {
            @Override
            public void countDownFinished() {
                //倒计时结束
                sequentialTiming();
            }
        });
        mBinding.countDownView.startCountDown();


        //禁止百度地图的手势
        UiSettings settings = mBinding.mapView.getMap().getUiSettings();
        settings.setAllGesturesEnabled(false);   //关闭一切手势操作
        settings.setOverlookingGesturesEnabled(false);//屏蔽双指下拉时变成3D地图
        settings.setZoomGesturesEnabled(false);//获取是否允许缩放手势返回:是否允许缩放手势

        mBinding.mapView.showScaleControl(false);  // 设置比例尺是否可见（true 可见/false不可见）
        mBinding.mapView.showZoomControls(false);  // 设置缩放控件是否可见（true 可见/false不可见）
        View child = mBinding.mapView.getChildAt(1); // 找到百度LOGO控件对象
        if ((child instanceof ImageView || child instanceof ZoomControls)) {
            child.setVisibility(View.INVISIBLE);  // 设置child这个控件是否可见（VISIBLE 可见/INVISIBLE不可见 /GONE 完全隐藏）
        }

        mBaiduMap = mBinding.mapView.getMap();
        double latitude = Double.parseDouble(orderParameters.addressData.get(0).latitude);
        double longitude = Double.parseDouble(orderParameters.addressData.get(0).longitude);

        LatLng ll = new LatLng(latitude, longitude);
        mapBuild = new MapStatus.Builder()
                .target(ll)
                .zoom(18f)
                .build();
        //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
        MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapBuild);
        //改变地图状态
        mBaiduMap.animateMapStatus(mMapStatusUpdate);

        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            //地图状态开始改变。
            public void onMapStatusChangeStart(MapStatus status) {

            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            //地图状态改变结束
            public void onMapStatusChangeFinish(MapStatus status) {
                //改变结束之后，获取地图可视范围的中心点坐标
                LatLng latLng = status.target;
                //拿到经纬度之后，就可以反地理编码获取地址信息了
                GeoCoder geocoder = GeoCoder.newInstance();
                geocoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
                    @Override
                    public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {
                    }

                    @Override
                    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                        String name = "";
                        if (reverseGeoCodeResult.getPoiRegionsInfoList() != null && reverseGeoCodeResult.getPoiRegionsInfoList().size() != 0)
                            name = reverseGeoCodeResult.getPoiRegionsInfoList().get(0).getRegionName();
                        else if (reverseGeoCodeResult.getPoiList() != null && reverseGeoCodeResult.getPoiList().size() != 0)
                            name = reverseGeoCodeResult.getPoiList().get(0).name;

                        if (TextUtils.isEmpty(name)) {
                            ToastUtils.showShort("定位失败，请重试或手动输入地址");
                            return;
                        }
//                        mBinding.tvName.setText(name);
//                        mBinding.tvAddress.setText(String.format("%s%s", reverseGeoCodeResult.getAddressDetail().city, reverseGeoCodeResult.getAddressDetail().district));
                    }
                });

                //这个要放在后面！！！！！！！
                LatLng point = new LatLng(latLng.latitude, latLng.longitude);
                geocoder.reverseGeoCode(new ReverseGeoCodeOption().location(point));

            }

            //地图状态变化中
            public void onMapStatusChange(MapStatus status) {
            }
        });

        //   initDanmu();

        mDanMuHelper = new DanMuHelper(this);
        // 当前房间内的弹幕
        mBinding.danmakuContainerRoom.prepare();
        mDanMuHelper.add(mBinding.danmakuContainerRoom);
        mBinding.danmakuContainerRoom.hideAllDanMuView(isBarrage);//显示或者隐藏弹幕

        Observable.interval(period, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new CommonObserver() {
            @Override
            public void onNext(Object o) {
                super.onNext(o);
                setDanmuLoop();
            }
        });

    }

    /**
     * 发送一条房间内的弹幕
     */
    private void addRoomDanmaku(Danmu danmu) {

        DanmakuEntity danmakuEntity = new DanmakuEntity();
        danmakuEntity.setType(DanmakuEntity.DANMAKU_TYPE_USERCHAT);
        danmakuEntity.setName(danmu.getUserName());
        danmakuEntity.setAvatar(danmu.getHeaderUrl());
        danmakuEntity.setLevel(23);
        danmakuEntity.setText("");

        if (mDanMuHelper != null) {
            mDanMuHelper.addDanMu(danmakuEntity, true);
        }
    }


    public void initDanmu() {


      /*  //下面是模拟每秒添加一个弹幕的过程
        HandlerThread ht = new HandlerThread("send danmu");
        ht.start();
        mDanmuAddHandler = new Handler(ht.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                runOnUiThread(() -> mBinding.danmuView.add(danmuList));
                //继续添加
                if (continueAdd) {
                    sendEmptyMessageDelayed(0, 1000);
                }
            }
        };*/
    }

    //顺计时
    public void sequentialTiming() {
        mBinding.tvTimeTitle.setText("接单顺计时");
        mBinding.countDownView.setVisibility(View.GONE);
        mBinding.llTimer.setVisibility(View.VISIBLE);
        mBinding.timer.start();
        mBinding.timer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {

            @Override
            public void onChronometerTick(Chronometer ch) {
                miss++;
                ch.setText(FormatMiss(miss));

            }
        });
    }

    @Override
    public void onResume() {
        mBinding.mapView.onResume();
        super.onResume();

      /*  mBinding.danmuView.startPlay(false);//true表示弹幕的垂直方向是固定的,false则随机
        continueAdd = true;
        mDanmuAddHandler.sendEmptyMessageDelayed(0, 6000);*/
    }

    @Override
    public void onPause() {
        mBinding.mapView.onPause();
        super.onPause();

       /* continueAdd = false;
        mDanmuAddHandler.removeMessages(0);*/
    }

    @Override
    public void onDestroy() {
        mBinding.mapView.onDestroy();
        super.onDestroy();
    }

    //取消订单
    @Override
    public void onCancelOrder() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", authorization);
        map.put("orderId", order);

        mViewModel.cancelOrder(map);
    }

    //打赏小费
    @Override
    public void onReward() {
        if (orderParameters.priceType == 0) {
            rewardPop = new RewardPop(this, marketPriceBean, authorization, amount, order);
            rewardPop.setRewardListener(amount -> {
                this.amount = amount;
                mBinding.tvPrice.setText(amount);
            });
            rewardPop.showPopupWindow(mBinding.getRoot());
        } else {
            modifyPricePop = new ModifyPricePop(this, marketPriceBean, authorization, amount, order);
            modifyPricePop.setModifyPriceListener(amount -> {
                this.amount = amount;
                mBinding.tvPrice.setText(amount);
            });
            modifyPricePop.showPopupWindow(mBinding.toolbar);
        }
    }

    //修改价格
    @Override
    public void onModifyPrice() {

    }

    @Override
    public void returnCancelOrder() {
        ToastUtils.showShort("取消成功");
        finish();
        AppActivityManager.getAppActivityManager().returnToActivity(HomeActivity.class);
    }

    //是否显示弹幕
    @Override
    public void onBarrage() {
        isBarrage = !isBarrage;
        mBinding.danmakuContainerRoom.hideAllDanMuView(isBarrage);
        if (isBarrage) {
            mBinding.ivBarrageState.setImageResource(R.drawable.ic_hidden_barrage);
        } else {
            mBinding.ivBarrageState.setImageResource(R.drawable.ic_display_barrage);
        }
    }

    // 将秒转化成小时分钟秒
    public String FormatMiss(int miss) {
        String hh = miss / 3600 > 9 ? miss / 3600 + "" : "0" + miss / 3600;
        String mm = (miss % 3600) / 60 > 9 ? (miss % 3600) / 60 + "" : "0" + (miss % 3600) / 60;
        String ss = (miss % 3600) % 60 > 9 ? (miss % 3600) % 60 + "" : "0" + (miss % 3600) % 60;
        return hh + ":" + mm + ":" + ss;
    }

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    //推给客户端 推送了多少位司机
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)//在ui线程执行
    public void onPushDriversNumEvent(PushDriversNumEvent event) {
        mBinding.tvTitle.setVisibility(View.VISIBLE);
        mBinding.tvTitle.setText(event.description);
    }

    //车主成功接单
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPushReceivedSuccessEvent(PushReceivedSuccessEvent event) {
        //接单成功
        IntentManager.toOrderStatusActivity(this, order,orderParameters, marketPriceBean, amount, true, orderTime);
        finish();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPushDanmuInfoEvent(PushDanmuInfoEvent event) {

        MessageBody messageInfo = JSONObject.parseObject(event.content, MessageBody.class);
        if (String.valueOf(messageInfo.orderId).equals(order)) {


            boolean isDanmuItem = false;
//            for (int i = danmuList.size() - 1; i >= 0; i--) {
            for (int i = 0; i < danmuList.size(); i++) {
                if (messageInfo.logo.equals(danmuList.get(i).getLogo())) {
                    isDanmuItem = true;

                    danmuList.get(i).setAmount(messageInfo.amount);
                    danmuList.get(i).setUserName(messageInfo.value);
                    addRoomDanmaku(danmuList.get(i));
                    Logger.d("1111111");
                }
            }


            if (!isDanmuItem) {
                Danmu danmu = new Danmu();
                danmu.setHeaderUrl(messageInfo.avatar);
                danmu.setUserName(messageInfo.value);
                danmu.setAmount(messageInfo.amount);
                danmu.setLogo(messageInfo.logo);
                // mBinding.danmuView.add(danmu);
                danmuList.add(danmu);
                addRoomDanmaku(danmu);
                Logger.d("111111122222");
            }


            BigDecimal max = danmuList.get(0).getAmount();//
            BigDecimal min = danmuList.get(0).getAmount();

            for (int i = 0; i < danmuList.size(); i++) {
                if (min.compareTo(danmuList.get(i).getAmount()) > 0) {//a大于b
                    min = danmuList.get(i).getAmount();
                }

                if (max.compareTo(danmuList.get(i).getAmount()) < 0) {//a小于b
                    max = danmuList.get(i).getAmount();
                }
            }

            BigDecimal priceHighest = new BigDecimal(mBinding.tvPriceHighest.getText().toString());
            BigDecimal priceMinimum = new BigDecimal(mBinding.tvPriceMinimum.getText().toString());

            Logger.d(min + "=价格1=" + priceMinimum);
            Logger.d(max + "=价格2=" + priceHighest);

            if (priceMinimum.compareTo(BigDecimal.ZERO) != 0) {
                if (min.compareTo(priceMinimum) > 0) {//a大于b
                    min = priceMinimum;
                }
            }

            if (priceHighest.compareTo(BigDecimal.ZERO) != 0) {
                if (max.compareTo(priceHighest) < 0) {//a小于b
                    max = priceHighest;
                }
            }

            mBinding.tvPriceHighest.setText(max + "");
            mBinding.tvPriceMinimum.setText(min + "");

        }

    }

    public void setDanmuLoop() {
        if (danmuList.size() != 0) {
            Danmu danmu = danmuList.get(num);

            addRoomDanmaku(danmu);
            int sizeNum = danmuList.size() - 1;
            Logger.d(num + "====测试数据啊==" + sizeNum);
            if (num == sizeNum) {
                num = 0;
            } else {
                num = num + 1;
            }
        }

    }
}
